package com.reebake.ideal.verify.code.handler;

import cn.hutool.core.util.ObjUtil;
import com.reebake.ideal.cache.helper.TimesCacheHelper;
import com.reebake.ideal.verify.code.core.VerifyCodeService;
import com.reebake.ideal.verify.code.core.VerifyCodeStorage;
import com.reebake.ideal.verify.code.entity.VerifyCodeEntity;
import com.reebake.ideal.verify.code.properties.VerifyCodeProperties;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;

@Setter
public class DefaultVerifyCodeService implements VerifyCodeService {
    @Autowired
    private VerifyCodeStorage verifyCodeStorage;
    @Autowired
    private VerifyCodeProperties verifyCodeProperties;
    private static final String TRY_TIMES_PREFIX = "verifyCode:tryTimes:";
    private static final int tryTimesExpiredIn = 300 * 1000;

    private TimesCacheHelper timesCacheHelper = new TimesCacheHelper(TRY_TIMES_PREFIX, tryTimesExpiredIn);

    @Override
    public void save(VerifyCodeEntity verifyCodeEntity) {
        verifyCodeStorage.save(verifyCodeEntity);
    }

    @Override
    public VerifyCodeEntity get(String sendKey) {
        return verifyCodeStorage.get(sendKey);
    }

    @Override
    public Boolean check(String sendKey, String userInputCode) {
        VerifyCodeEntity verifyCodeEntity = this.get(sendKey);
        if (ObjUtil.isNull(verifyCodeEntity)) {
            return false;
        }
        String verifyCode = verifyCodeEntity.getVerifyCode();
        // 验证次数校验
        long tryTimes = timesCacheHelper.getTimes(sendKey);
        if(tryTimes > verifyCodeProperties.getMaxTryTimes()) {
            return false;
        }
        boolean result = userInputCode.equalsIgnoreCase(verifyCode);
        if (result) {
            verifyCodeStorage.remove(sendKey);
            timesCacheHelper.remove(sendKey);
        }else {
            timesCacheHelper.increase(sendKey,tryTimes + 1);
        }
        return result;
    }

}
